//
//  SiterAPI.m
//  sHome
//
//  Created by TracyHenry on 2022/8/15.
//  Copyright © 2022年 SiterWell. All rights reserved.
//

#import "SiterAPI.h"
#import "Netability.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#define SiterUid @"SiterUid"
#define SiterAccessToken @"SiterAccessToken"
#define SiterrefreshToken @"SiterRefreshToken"
@interface Siter()
    
@end

@implementation Siter(Authorization)
#pragma mark -method(用户信息数据读写)
-(void)setUid:(NSNumber *)uid{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    [config setValue:uid forKey:SiterUid];
    [config synchronize];
}

-(NSNumber *)uid{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSNumber *responseObject = [config objectForKey:SiterUid];
    return responseObject;
}


-(void)setAccess_token:(NSString *)access_token{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    [config setValue:access_token forKey:SiterAccessToken];
    [config synchronize];
}

-(NSString *)access_token{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *responseObject = [config objectForKey:SiterAccessToken];
    return responseObject;
}

-(void)setRefresh_token:(NSString *)refresh_token{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    [config setValue:refresh_token forKey:SiterrefreshToken];
    [config synchronize];
}

-(NSString *)refresh_token{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *responseObject = [config objectForKey:SiterrefreshToken];
    return responseObject;
}
@end

@implementation Siter(Cloud)


-(AFHTTPSessionManager *)sessionWithDefaultAuthorization{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    manager.requestSerializer.timeoutInterval = 10.f;
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manager.responseSerializer = response;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *token = [self access_token];
    if(token == nil){
        token = @"";
    }
    [manager.requestSerializer setValue:[@"Bearer " stringByAppendingString:token] forHTTPHeaderField:@"Authorization"];
    return manager;
}


@end


@implementation Siter(User)

-(void) setOnlineSite:(NSString* )domain{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
        [config setObject:domain forKey:@"siter_domain"];
        [config synchronize];
}

-(NSString *)getDomain{
   NSString *domain = [[NSUserDefaults standardUserDefaults] objectForKey:@"siter_domain"];
   return domain;
}

-(void) setRegisterToken:(NSString* )registerToken{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
        [config setObject:registerToken forKey:@"register_token"];
        [config synchronize];
}

-(NSString *)getRegisterToken{
   NSString *domain = [[NSUserDefaults standardUserDefaults] objectForKey:@"register_token"];
   return domain;
}


-(NSString *)getTourlistUsername{
   NSString *siter_tourlist_username = [[NSUserDefaults standardUserDefaults] objectForKey:@"siter_tourlist_username"];
    if([self isBlankString:siter_tourlist_username]){
        NSString *firstname = [self GUIDString];
        firstname = [firstname stringByReplacingOccurrencesOfString:@"-" withString:@""];
        [[NSUserDefaults standardUserDefaults] setObject:firstname forKey:@"siter_tourlist_username"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        return firstname;
    }else{
        return siter_tourlist_username;
    }
   
}

-(void) oneKeyCreateAndLogin:(NSString*)userName callbcak:(void(^)(id user,NSError*)) block{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *packageName = [infoDic objectForKey:@"CFBundleIdentifier"];
        NSDictionary *param = @{
             @"pid" : [Siter sharedInstance].pid,
             @"username" : userName,
             @"app_tid" : packageName,
             @"login_type" : @1
             };
//
//        NSString *host = [self getDomain];
         
         [[self sessionWithDefaultAuthorization] POST:@"https://mqt3yabvub.execute-api.us-west-2.amazonaws.com/default/appLogin" parameters:param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSNumber *codee = responseObject[@"code"];
             int code = [codee intValue];
             if(code==200){
                 [self setAccess_token:responseObject[@"data"][@"access_token"]];
                 [self setUid:responseObject[@"data"][@"user_id"]];
                 [self setRefresh_token:responseObject[@"data"][@"refresh_token"]];
                 !block ?: block(responseObject, nil);
             }else{
                 NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:code userInfo:nil];
                 !block ?: block(nil, error);
             }

             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 !block ?: block(nil, error);
             }];
    
}

-(void)refreshacTokenwithCallbcak:(void(^)(id user,NSError*)) block{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *refreshToken = [config objectForKey:SiterrefreshToken];
    NSDictionary *param = @{
         @"refresh_token" : refreshToken,
         @"user_id": self.uid
         };
    NSString *host = [self getDomain];
    [[self sessionWithDefaultAuthorization] POST:[host stringByAppendingString:@"/refreshToken"] parameters:param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSNumber *codee = responseObject[@"code"];
        if(codee==nil){
            NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:-1 userInfo:nil];
            !block ?: block(nil, error);
        }else{
            int code = [codee intValue];
            if(code==200){
                [self setAccess_token:responseObject[@"data"][@"access_token"]];
                !block ?: block(responseObject, nil);
            }else{
                NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:code userInfo:nil];
                !block ?: block(nil, error);
            }
        }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            !block ?: block(nil, error);
        }];
}


-(void) logout{
    [self setUid:nil];
    [self setAccess_token:nil];
    [self setRefresh_token:nil];
}

-(BOOL) isBlankString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        
        return YES;
        
    }
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        return YES;
        
    }
    if ([string isEqualToString:@"(null)"]) {
        
        return YES;
        
    }
    
    return NO;
    
}

- (NSString*)GUIDString {
    CFUUIDRef newUniqueID = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef newUniqueIDString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueID);
    NSString *guid = (__bridge NSString *)newUniqueIDString;
    CFRelease(newUniqueIDString);
    CFRelease(newUniqueID);
    return([guid lowercaseString]);
}

@end

